/*package com.lhfeiyu.service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONObject;
import com.lhfeiyu.dao.WholesaleMapper;
import com.lhfeiyu.dao.GoodsMapper;
import com.lhfeiyu.dao.GoodsOffersMapper;
import com.lhfeiyu.dao.NoticeMapper;
import com.lhfeiyu.dao.OrderGoodsMapper;
import com.lhfeiyu.dao.OrderInfoMapper;
import com.lhfeiyu.dao.ShopMapper;
import com.lhfeiyu.dao.UserMapper;
import com.lhfeiyu.po.Goods;
import com.lhfeiyu.po.GoodsOffers;
import com.lhfeiyu.po.Notice;
import com.lhfeiyu.po.OrderGoods;
import com.lhfeiyu.po.OrderInfo;
import com.lhfeiyu.po.Shop;
import com.lhfeiyu.po.User;
import com.lhfeiyu.po.UserFund;
import com.lhfeiyu.po.Wholesale;
import com.lhfeiyu.service.base.CommonService;
import com.lhfeiyu.service.base.UserFundService;
import com.lhfeiyu.tools.base.ActionUtil;
import com.lhfeiyu.tools.base.Check;
import com.lhfeiyu.tools.base.CommonGenerator;
import com.lhfeiyu.tools.base.Result;

@Service
public class GoodsOffersService extends CommonService<GoodsOffers>{
	@Autowired
	GoodsOffersMapper mapper;
	@Autowired
	UserMapper userMapper;
	@Autowired
	GoodsMapper goodsMapper;
	@Autowired
	WholesaleMapper wholesaleMapper;
	@Autowired
	ShopMapper shopMapper;
	@Autowired
	NoticeMapper noticeMapper;
	@Autowired
	OrderInfoMapper orderInfoMapper;
	@Autowired
	OrderGoodsMapper orderGoodsMapper;
	@Autowired
	UserFundService userFundService;
	
	public JSONObject addGoodsOffer(JSONObject json, User user, GoodsOffers goodsOffers){
		int userId = user.getId();
		String username = user.getUsername();
		user = userMapper.selectByPrimaryKey(userId);
		String userPhone = user.getPhone();
		Integer goodsId = goodsOffers.getGoodsId();
		Integer goodsOfferId = goodsOffers.getId();
		if(null == goodsId && null == goodsOfferId){
			return Result.failure(json, "缺少出价信息编号，无法进行操作", null);
		}
		if(null == goodsId){
			GoodsOffers gf = mapper.selectByPrimaryKey(goodsOfferId);
			if(null == gf){
				return Result.failure(json, "本次出价信息已经不存在", null);
			}
			goodsId = gf.getGoodsId();
		}
		
		Date date = new Date();
		if(null == userPhone || "".equals(userPhone)){
			json.put("noPhone", "noPhone");
			return Result.failure(json, "请先绑定手机号码", null);
		}
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("userId", userId);
		List<UserFund> userFundList = userFundService.selectListByCondition(map);
		UserFund userFund = userFundList.get(0);
		if(userFundList.size() > 0){
			if(null == userFund.getPayPassword() || "".equals(userFund.getPayPassword()) ){
				json.put("noPayPassword", "noPayPassword");
				return Result.failure(json, "请先设置支付密码", null);
			}
		}
		map.clear();
		map.put("goodsId", goodsId);
		List<Goods> goodsList = goodsMapper.selectListByCondition(map);
		if(!Check.isNotNull(goodsList)){
		    return Result.failure(json, "该商品已经不存在，无法进行报价", null);
		}
		//TODO 判断是否已经出售（商品状态）
		Goods goods = goodsList.get(0);
		Integer goodsStatus = goods.getMainStatus();
		if(goodsStatus == 75){
		    return Result.failure(json, "该商品已经下架，无法进行报价和出售", null);
		}else if(goodsStatus == 77){
		    return Result.failure(json, "该商品已经售出，无法进行报价和出售", null);
		}else if(goodsStatus == 78){
		    return Result.failure(json, "该商品处于冻结中，无法进行报价和出售", null);
		}
		Integer goodsOwnerId = goods.getUserId();
		String goodsName = goods.getGoodsName();
		if(null == goodsOwnerId || userId == goodsOwnerId.intValue()){
			return Result.failure(json, "不能对自己的藏品进行报价", null);
		}
		BigDecimal offerPrice = goodsOffers.getOfferPrice();//报价
		double price = 0;
		if(null != offerPrice){//先判断是否为null
			offerPrice = offerPrice.setScale(2, BigDecimal.ROUND_HALF_UP);//设置保留两位小数
			price = offerPrice.doubleValue();
			if(price <= 0 || price > 100000){//判读是否大于0
			    return Result.failure(json, "报价价格目前只能在1~100000元范围之内", null);
			}
		}else{
			return Result.failure(json, "请填写您对该商品的报价价格", null);
		}
		goodsOffers.setId(null);
		goodsOffers.setMainStatus(1);//状态(1.未进行2.流拍,3.成交)
		goodsOffers.setGoodsId(goodsId);
		goodsOffers.setShopId(goods.getShopId());
		goodsOffers.setUserId(userId);
		goodsOffers.setUsername(username);
		goodsOffers.setOfferStatus(1);//报价的状态（1未阅读，2已通知，3已阅读,4未同意，5已同意,6已生成订单,7交易中，8交易已完成,9已取消订单,10已退货）
		goodsOffers.setCreatedAt(date);
		goodsOffers.setCreatedBy(username);
		mapper.insert(goodsOffers);
		String content = "【"+goodsName+"】该商品您出价:"+price+"元";
		String content1 = "【"+username+"】对该商品【"+goodsName+"】出价:"+price+"元";

		commonNotice(content,content,userId,goodsId);//买家出价消息
		commonNotice(content1,content1, goodsOwnerId,goodsId);//卖家消息
		
		return Result.success(json, null, null);
	}
	
	public JSONObject disgreeGoodsOffer(JSONObject json, User user, Integer goodsOfferId){
		Date date = new Date();
		GoodsOffers goodsOffers = mapper.selectByPrimaryKey(goodsOfferId);
		if(null == goodsOffers){
			return Result.failure(json, "本次出价信息已经不存在", null);
		}
		Integer goodsId = goodsOffers.getGoodsId();
		
		Map<String,Object> map = new HashMap<String,Object>();
		map.clear();
		map.put("goodsId", goodsId);
		List<Goods> goodsList = goodsMapper.selectListByCondition(map);
		if(!Check.isNotNull(goodsList)){
		    return Result.failure(json, "该商品已经不存在，无法进行报价", null);
		}
		Goods goods = goodsList.get(0);
		Integer userId  = user.getId();
		Integer goodsOwnerId = goods.getUserId();
		if(null == goodsOwnerId || userId != goodsOwnerId.intValue()){
			return Result.failure(json, "您没有权限修改该商品报价", null);
		}
		String goodsName = goods.getGoodsName();
		String content = "【"+goodsName+"】您的报价（"+goodsOffers.getOfferPrice()+"元）被卖家拒绝了";
		commonNotice(content, content, goodsOffers.getUserId(), goodsId);
		
		goodsOffers.setPromoteUserId(null);//新增报价时生成推广人信息，修改时不修改推广人信息
		goodsOffers.setPromoteUsername(null);
		goodsOffers.setPromoteUserSerial(null);
		goodsOffers.setOfferPrice(null);//出价被拒绝时不更新报价
		goodsOffers.setOfferStatus(4);//报价的状态（1未阅读，2已通知，3已阅读,4未同意，5已同意,6已生成订单,7交易中，8交易已完成,9已取消订单,10已退货）
		goodsOffers.setUpdatedAt(date);
		goodsOffers.setOperateTime(date);
		goodsOffers.setUpdatedBy(user.getUsername());
		mapper.updateByPrimaryKeySelective(goodsOffers);//更新报价状态和成交价格
		
		return Result.success(json, "操作成功", null);
	}
	
	public JSONObject agreeGoodsOffer(JSONObject json, User user, GoodsOffers goodsOffers){
		Date date = new Date();
		GoodsOffers db_goodsOffers = mapper.selectByPrimaryKey(goodsOffers.getId());
		if(null == goodsOffers.getId() || null == goodsOffers){
			return Result.failure(json, "本次出价信息已经不存在", null);
		}
		if(null != goodsOffers.getOfferStatus() && goodsOffers.getOfferStatus() == 6){////报价的状态（1未阅读，2已通知，3已阅读,4未同意，5已同意,6已生成订单,7交易中，8交易已完成,9已取消订单,10已退货）
			return Result.failure(json, "本次报价已经生成订单", null);
		}
		Integer goodsId = db_goodsOffers.getGoodsId();
		Map<String,Object> map = new HashMap<String,Object>();
		map.clear();
		map.put("goodsId", goodsId);
		List<Goods> goodsList = goodsMapper.selectListByCondition(map);
		if(!Check.isNotNull(goodsList)){
		    return Result.failure(json, "该商品已经不存在，无法进行报价", null);
		}
		Goods goods = goodsList.get(0);
		Integer userId  = user.getId();
		Integer goodsOwnerId = goods.getUserId();
		if(null == goodsOwnerId || userId != goodsOwnerId.intValue()){
			return Result.failure(json, "您没有权限修改该商品报价", null);
		}
		String goodsName = goods.getGoodsName();
		
		goodsOffers.setPromoteUserId(null);//新增报价时生成推广人信息，修改时不修改推广人信息
		goodsOffers.setPromoteUsername(null);
		goodsOffers.setPromoteUserSerial(null);
		BigDecimal dealPrice = goodsOffers.getDealPrice();//最终报价
		Integer buyerId = db_goodsOffers.getUserId();
		String buyerName = db_goodsOffers.getUserName();
		double dPrice = 0;
		//最终结果
		if(null != dealPrice){//先判断是否为null
			dealPrice = dealPrice.setScale(2, BigDecimal.ROUND_HALF_UP);//设置保留两位小数
			dPrice = dealPrice.doubleValue();
			if(dPrice <= 0 || dPrice > 1000000){//判读是否大于0
				json.put("status", "failure");
			    json.put("msg", "最终报价价格目前只能在1~1000000元范围之间");
			    return json;
			}
		}else{
			json.put("status", "failure");
		    json.put("msg", "请填写最终报价价格");
			return json;
		}
		//TODO tempHide - 不计算推广费
		BigDecimal promoteBenifitMoney = null;
		Integer bounsType = goods.getBonusTypeId();
		BigDecimal bouns = goods.getBonus();
		
		if(null != bounsType){//判读是否有推广
			if(bounsType == 1){//按金额算推广费
				promoteBenifitMoney = bouns;
			}
			if(bounsType == 2){//按百分比算推广费
				BigDecimal shareFee = bouns.divide(new BigDecimal(100));
				promoteBenifitMoney = shareFee.multiply(dealPrice);
			}
			promoteBenifitMoney = promoteBenifitMoney.setScale(2, BigDecimal.ROUND_HALF_UP);//设置保留两位小数
			if(promoteBenifitMoney.doubleValue() <= dPrice){//推广金额不能超过商品金额本身
				json = commonFundService.freezeMoney(null, promoteBenifitMoney, buyerId, buyerName, 148, 0, "SYS", json, false, getLinkUrl(goodsId));
				if(json.containsKey("error_desc")){ return json; }
			}
		}
		OrderInfo orderInfo =  new OrderInfo();
		orderInfo.setOrderSn(CommonGenerator.getSerialByDate("od"));
		orderInfo.setUserId(buyerId);
		orderInfo.setUsername(buyerName);
		orderInfo.setPayStatus(1);//支付状态;1未付款;2付款中;3已付款
		orderInfo.setOrderStatus(1);//订单的状态;1未完成,2已完成,3已取消,4无效,5退货6，申请退货
		orderInfo.setShippingStatus(1);//商品配送情况;1未发货,2已发货,3已收货,4退货
		orderInfo.setCreatedAt(date);
		orderInfo.setCreatedBy("-SYS-");
		orderInfo.setMainStatus(1);//状态（1未结束订单，2已结束订单，3无效订单）
		//orderInfo.setUsername(username);
		orderInfoMapper.insert(orderInfo);//生成订单
		Integer orderId = orderInfo.getId();
		//String goodsName = goods.getGoodsName();
		OrderGoods orderGoods = new OrderGoods();
		orderGoods.setGoodsType(1);//普通商品
		orderGoods.setGoodsFrom(2);//店铺
		orderGoods.setOrderId(orderId);
		orderGoods.setGoodsId(db_goodsOffers.getGoodsId());
		orderGoods.setGoodsName(goodsName);
		orderGoods.setGoodsSn(goods.getGoodsSn());
		orderGoods.setPromoteUserId(db_goodsOffers.getPromoteUserId());
		orderGoods.setPromoteUsername(db_goodsOffers.getPromoteUserSerial());
		//orderGoods.setPromoteBenifitMoney(promoteBenifitMoney);
		orderGoods.setGoodsNumber(1);
		orderGoods.setMainStatus(1);
		orderGoods.setCreatedAt(date);
		orderGoods.setCreatedBy("-SYS-");
		orderGoods.setShopPrice(dealPrice);
		orderGoodsMapper.insert(orderGoods);//生成商品订单信息
		//冻结商品
		goods.setMainStatus(78);//dict78:冻结中
		goods.setUpdatedAt(date);
		goods.setUpdatedBy("-SYS-");
		goodsMapper.updateByPrimaryKeySelective(goods);
		//发消息通知
		String title = "恭喜您该商品【"+goodsName+"】报价卖家已经同意";
		String content = "恭喜您该商品【"+goodsName+"】报价卖家已经同意，系统已经为您生成订单，可以到个人中心查看订单并付款";
		commonNotice(title, content, buyerId, goodsId);//userId
		//sellerId
		title = "恭喜您该商品【"+goodsName+"】已成功生成订单";
		content = "恭喜您该商品【"+goodsName+"】已成功生成订单";
		commonNotice(title, content, goodsOwnerId, goodsId);
		goodsOffers.setOfferStatus(6);////报价的状态（1未阅读，2已通知，3已阅读,4未同意，5已同意,6已生成订单,7交易中，8交易已完成,9已取消订单,10已退货）
		mapper.updateByPrimaryKeySelective(goodsOffers);
		
		return Result.success(json, "操作成功", null);
	}
	
	private void commonNotice(String title,String content,Integer receiverId,Integer goodsId){
		Goods goods = goodsMapper.selectByPrimaryKey(goodsId);
		Integer moduleId = goods.getModuleId();
		Integer shopId = goods.getShopId();
		Notice notice = new Notice();
		notice.setSerial(CommonGenerator.getSerialByDate("n"));
		notice.setReceiverId(receiverId);//买家
		notice.setContent(content);
		Map<String,Object> map = new HashMap<String,Object>();
		map.put("id", shopId);
		if(moduleId != null){
			List<Wholesale> wholesalesList = wholesaleMapper.selectListByCondition(map);
			if(wholesalesList.size() > 0){
				Wholesale wholesales = wholesalesList.get(0);
				Integer wholesalesUserId = wholesales.getUserId();
				String userSerial = wholesales.getUserSerial();
				String linkUrl = "/wsg/"+goodsId+"/"+shopId+"/"+wholesalesUserId+"?moduleId="+moduleId+"&r="+userSerial;
				notice.setLinkUrl(linkUrl);
			}
		}else{
			List<Shop> shopList = shopMapper.selectListByCondition(map);
			if(shopList.size() > 0){
				Shop shop = shopList.get(0); 
				String userSerial = shop.getUserSerial();
				String linkUrl = "/goods/"+goodsId+"?shopId="+shopId+"&r="+userSerial;
				notice.setLinkUrl(linkUrl);
			}
		}
		notice.setReadStatus(1);//未阅读
		notice.setTypeId(33);//新订单生成
		notice.setTitle(title);
		notice.setCreatedAt(new Date());
		notice.setCreatedBy("-SYS-");
		noticeMapper.insert(notice);//新增通知
	}
	
	private String  getLinkUrl(Integer goodsId){
		String linkUrl = null;
		Goods goods = goodsMapper.selectByPrimaryKey(goodsId);
		if(null != goods && !"".equals(goods)){
			Integer moduleId = goods.getModuleId();
			Integer shopId = goods.getShopId();
			Map<String,Object> map = new HashMap<String,Object>();
			map.put("id", shopId);
			if(moduleId != null){
				List<Wholesale> wholesalesList = wholesaleMapper.selectListByCondition(map);
				if(wholesalesList.size() > 0){
					Wholesale wholesales = wholesalesList.get(0);
					Integer wholesalesUserId = wholesales.getUserId();
					String userSerial = wholesales.getUserSerial();
					linkUrl = "/wsg/"+goodsId+"/"+shopId+"/"+wholesalesUserId+"?moduleId="+moduleId+"&r="+userSerial;
				}
			}else{
				List<Shop> shopList = shopMapper.selectListByCondition(map);
				if(shopList.size() > 0){
					Shop shop = shopList.get(0); 
					String userSerial = shop.getUserSerial();
					linkUrl = "/goods/"+goodsId+"?shopId="+shopId+"&r="+userSerial;
				}
			}
		}
		return linkUrl;
	}
	
}
*/